<template>
  <div class="ansible-audit-container">
    <!-- 星空背景 -->
    <div class="starry-background">
      <div class="stars"></div>
      <div class="stars2"></div>
      <div class="stars3"></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="audit-content">
      <!-- 页面标题 -->
      <div class="page-header glass-effect">
        <div class="header-content">
          <div class="title-section">
            <h1 class="page-title">
              <i class="fa fa-cube"></i>
              Docker容器管理
            </h1>
            <p class="page-subtitle">管理Docker容器的启停、查看、删除等操作</p>
          </div>
          <div class="stats-section">
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.total_containers || 0 }}</div>
              <div class="stat-label">容器总数</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.running_containers || 0 }}</div>
              <div class="stat-label">运行中</div>
            </div>
            <div class="stat-card glass-effect">
              <div class="stat-number">{{ statistics.stopped_containers || 0 }}</div>
              <div class="stat-label">已停止</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="search-filters glass-effect">
        <el-form inline class="search-form">
          <el-form-item>
            <el-select v-model="selectedServer" placeholder="选择Docker服务器" class="server-select">
              <el-option
                v-for="server in dockerServers"
                :key="server.id"
                :label="server.name"
                :value="server.id"
              />
            </el-select>
            <el-button type="primary" @click="refreshContainers" class="glass-button refresh-button" :loading="loading">
              <i class="fa fa-refresh"></i>
              刷新容器
            </el-button>
            <el-button @click="showCreateContainer" class="glass-button add-button">
              <i class="fa fa-plus"></i>
              创建容器
            </el-button>
            <el-button @click="cleanupContainers" class="glass-button delete-button">
              <i class="fa fa-trash"></i>
              清理停止的容器
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 容器列表 -->
      <div class="audit-table-section glass-effect">
        <div class="section-title">
          <i class="fa fa-cube"></i>
          Docker容器列表
        </div>

        <el-table
          :data="containers"
          style="width: 100%"
          v-loading="loading"
          row-class-name="audit-row"
          class="audit-table"
        >
          <el-table-column prop="name" label="容器名称" min-width="150">
            <template #default="scope">
              <div class="config-name">
                <i class="fa fa-cube"></i>
                {{ scope.row.name }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="image" label="镜像" min-width="200" />

          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag
                :type="getStatusType(scope.row.status)"
                size="small"
              >
                {{ getStatusText(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="ports" label="端口映射" width="140">
            <template #default="scope">
              <span class="port-text">
                {{ formatPorts(scope.row.ports) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="created" label="创建时间" width="140">
            <template #default="scope">
              <span class="time-text">
                {{ formatTime(scope.row.created) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="530" :show-overflow-tooltip="false">
            <template #default="scope">
              <div class="action-buttons">
                <el-button
                  v-if="scope.row.status === 'running'"
                  @click="stopContainer(scope.row)"
                  size="small"
                  class="glass-button delete-button"
                >
                  <i class="fa fa-stop"></i>
                  停止
                </el-button>
                <el-button
                  v-else
                  @click="startContainer(scope.row)"
                  size="small"
                  class="glass-button add-button"
                >
                  <i class="fa fa-play"></i>
                  启动
                </el-button>
                <el-button
                  @click="restartContainer(scope.row)"
                  size="small"
                  class="glass-button sync-button"
                >
                  <i class="fa fa-refresh"></i>
                  重启
                </el-button>
                <el-button
                  @click="viewLogs(scope.row)"
                  size="small"
                  class="glass-button import-button"
                >
                  <i class="fa fa-file-text"></i>
                  日志
                </el-button>
                <el-button
                  @click="execContainer(scope.row)"
                  size="small"
                  class="glass-button sync-button"
                >
                  <i class="fa fa-terminal"></i>
                  终端
                </el-button>
                <el-button
                  @click="inspectContainer(scope.row)"
                  size="small"
                  class="glass-button info-button"
                >
                  <i class="fa fa-info-circle"></i>
                  详情
                </el-button>
                <el-button
                  @click="deleteContainer(scope.row)"
                  size="small"
                  class="glass-button delete-button"
                >
                  <i class="fa fa-trash"></i>
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>

  <!-- 日志查看对话框 -->
  <el-dialog
    v-model="logDialogVisible"
    :title="logDialogTitle"
    width="90%"
    top="5vh"
    class="glass-dialog log-dialog"
    destroy-on-close
  >
    <template #header="{ titleId, titleClass }">
      <div class="log-header">
        <div class="log-title">
          <i class="fa fa-file-text log-icon"></i>
          <span :id="titleId" :class="titleClass">{{ logDialogTitle }}</span>
        </div>
        <div class="log-controls">
          <el-switch
            v-model="realTimeLogs"
            @change="toggleRealTimeLogs"
            active-text="实时"
            inactive-text="静态"
            active-color="#a4f4ba"
            inactive-color="#666"
            size="small"
            style="margin-right: 12px;"
          />
          <el-button @click="refreshLogs" size="small" class="glass-button" :disabled="realTimeLogs">
            <i class="fa fa-refresh"></i>
            刷新
          </el-button>
          <el-button @click="clearLogs" size="small" class="glass-button">
            <i class="fa fa-trash"></i>
            清空
          </el-button>
        </div>
      </div>
    </template>

    <div class="log-container">
      <div class="log-content" ref="logContentRef">
        <pre class="log-text">{{ logContent }}</pre>
      </div>
    </div>

    <template #footer>
      <div class="log-footer">
        <div class="log-info">
          <span class="log-tip">
            <i class="fa fa-info-circle"></i>
            <span v-if="realTimeLogs">
              实时日志追踪中，自动滚动到底部
              <span class="log-status" :class="{ connected: logsWebsocketConnected }">
                <i class="fa fa-circle"></i>
                {{ logsWebsocketConnected ? '已连接' : '未连接' }}
              </span>
            </span>
            <span v-else>
              显示最近 {{ logLines }} 行日志，自动滚动到底部
            </span>
          </span>
        </div>
        <div class="log-actions">
          <el-button @click="scrollToTop" class="glass-button">
            <i class="fa fa-arrow-up"></i>
            顶部
          </el-button>
          <el-button @click="scrollToBottom" class="glass-button">
            <i class="fa fa-arrow-down"></i>
            底部
          </el-button>
          <el-button @click="closeLogsDialog" class="glass-button danger">
            <i class="fa fa-times"></i>
            关闭
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>

  <!-- 容器终端对话框 -->
  <el-dialog
    v-model="terminalDialogVisible"
    :title="terminalDialogTitle"
    width="95%"
    top="3vh"
    class="glass-dialog terminal-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    destroy-on-close
  >
    <template #header="{ titleId, titleClass }">
      <div class="terminal-header">
        <div class="terminal-title">
          <i class="fa fa-terminal terminal-icon"></i>
          <span :id="titleId" :class="titleClass">{{ terminalDialogTitle }}</span>
        </div>
        <div class="terminal-controls">
          <div class="terminal-status" :class="{ connected: terminalConnected }">
            <i class="fa fa-circle"></i>
            <span>{{ terminalConnected ? '已连接' : '未连接' }}</span>
          </div>
        </div>
      </div>
    </template>

    <div class="terminal-container">
      <div id="terminal" class="terminal"></div>
    </div>

    <template #footer>
      <div class="terminal-footer">
        <div class="terminal-info">
          <span class="terminal-tip">
            <i class="fa fa-lightbulb"></i>
            提示：使用 Ctrl+C 中断命令，输入 exit 退出容器
          </span>
        </div>
        <div class="terminal-actions">
          <el-button @click="cleanupTerminal(); terminalDialogVisible = false" class="glass-button danger">
            <i class="fa fa-times"></i>
            断开连接
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>

  <!-- 容器详情对话框 -->
  <el-dialog
    v-model="inspectDialogVisible"
    :title="inspectDialogTitle"
    width="90%"
    top="5vh"
    class="glass-dialog inspect-dialog"
    destroy-on-close
  >
    <template #header="{ titleId, titleClass }">
      <div class="inspect-header">
        <div class="inspect-title">
          <i class="fa fa-info-circle inspect-icon"></i>
          <span :id="titleId" :class="titleClass">{{ inspectDialogTitle }}</span>
        </div>
        <div class="inspect-controls">
          <el-button @click="refreshInspect" size="small" class="glass-button">
            <i class="fa fa-refresh"></i>
            刷新
          </el-button>
          <el-button @click="copyInspectData" size="small" class="glass-button">
            <i class="fa fa-copy"></i>
            复制
          </el-button>
        </div>
      </div>
    </template>

    <div class="inspect-container">
      <div class="inspect-content" ref="inspectContentRef">
        <pre class="inspect-text">{{ inspectContent }}</pre>
      </div>
    </div>

    <template #footer>
      <div class="inspect-footer">
        <div class="inspect-info">
          <span class="inspect-tip">
            <i class="fa fa-info-circle"></i>
            容器详细配置信息（JSON格式）
          </span>
        </div>
        <div class="inspect-actions">
          <el-button @click="scrollInspectToTop" class="glass-button">
            <i class="fa fa-arrow-up"></i>
            顶部
          </el-button>
          <el-button @click="scrollInspectToBottom" class="glass-button">
            <i class="fa fa-arrow-down"></i>
            底部
          </el-button>
          <el-button @click="closeInspectDialog" class="glass-button danger">
            <i class="fa fa-times"></i>
            关闭
          </el-button>
        </div>
      </div>
    </template>
  </el-dialog>

  <!-- 创建容器对话框 -->
  <el-dialog
    v-model="createDialogVisible"
    title="创建容器"
    width="900px"
    class="glass-dialog"
    :close-on-click-modal="false"
    :destroy-on-close="true"
  >
    <div class="dialog-form-glass">
      <el-tabs v-model="activeTab" class="run-container-tabs">
        <!-- 基本配置 -->
        <el-tab-pane label="基本配置" name="basic">
          <el-form :model="createForm" label-width="140px" class="form-glass">
            <el-form-item label="镜像来源" required>
              <el-radio-group v-model="createForm.image_source" class="image-source-group">
                <el-radio label="local" class="image-source-radio">
                  <div class="image-source-option">
                    <i class="fa fa-hdd-o"></i>
                    <div class="image-source-content">
                      <div class="image-source-title">选择本地镜像</div>
                      <div class="image-source-desc">从当前服务器已有的镜像中选择</div>
                    </div>
                  </div>
                </el-radio>
                <el-radio label="manual" class="image-source-radio">
                  <div class="image-source-option">
                    <i class="fa fa-cloud-download"></i>
                    <div class="image-source-content">
                      <div class="image-source-title">手动输入镜像</div>
                      <div class="image-source-desc">输入镜像名称，如不存在会自动拉取</div>
                    </div>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item v-if="createForm.image_source === 'local'" label="选择镜像" required>
              <el-select v-model="createForm.image_name" class="glass-select" style="width: 100%" placeholder="请选择镜像">
                <el-option
                  v-for="image in availableImages"
                  :key="`${image.repository}:${image.tag}`"
                  :label="`${image.repository}:${image.tag}`"
                  :value="`${image.repository}:${image.tag}`"
                >
                  <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>{{ image.repository }}:{{ image.tag }}</span>
                    <span style="color: #a4f4ba; font-size: 12px;">{{ image.size }}</span>
                  </div>
                </el-option>
              </el-select>
              <div class="form-tip">选择要运行的本地镜像</div>
            </el-form-item>

            <el-form-item v-if="createForm.image_source === 'manual'" label="镜像名称" required>
              <el-input
                v-model="createForm.manual_image_name"
                placeholder="例如: nginx:latest, mysql:8.0, redis:alpine"
                class="glass-input"
              />
              <div class="form-tip">
                输入完整的镜像名称，格式：[仓库/]镜像名[:标签]<br/>
                如果本地不存在，Docker会自动从仓库拉取
              </div>
            </el-form-item>

            <el-form-item label="容器名称">
              <el-input
                v-model="createForm.container_name"
                placeholder="可选，留空则自动生成"
                class="glass-input"
              />
              <div class="form-tip">为容器指定一个名称，便于管理</div>
            </el-form-item>

            <el-form-item label="重启策略">
              <el-select v-model="createForm.restart_policy" class="glass-select" style="width: 100%">
                <el-option label="不重启 (no)" value="no" />
                <el-option label="总是重启 (always)" value="always" />
                <el-option label="除非手动停止 (unless-stopped)" value="unless-stopped" />
                <el-option label="失败时重启 (on-failure)" value="on-failure" />
              </el-select>
              <div class="form-tip">容器退出时的重启策略</div>
            </el-form-item>

            <el-form-item label="运行选项">
              <div class="run-options">
                <el-checkbox v-model="createForm.auto_remove" class="run-option-checkbox">
                  <span class="option-label">自动删除 (--rm)</span>
                  <div class="option-desc">容器停止后自动删除</div>
                </el-checkbox>
                <el-checkbox v-model="createForm.privileged" class="run-option-checkbox">
                  <span class="option-label">特权模式 (--privileged)</span>
                  <div class="option-desc">给予容器扩展权限</div>
                </el-checkbox>
              </div>
            </el-form-item>

            <el-form-item label="运行用户">
              <el-input
                v-model="createForm.user"
                placeholder="例如: 1000:1000 或 root"
                class="glass-input"
              />
              <div class="form-tip">指定容器内运行进程的用户，格式：用户ID:组ID</div>
            </el-form-item>

            <el-form-item label="工作目录">
              <el-input
                v-model="createForm.working_dir"
                placeholder="例如: /app"
                class="glass-input"
              />
              <div class="form-tip">设置容器内的工作目录</div>
            </el-form-item>

            <el-form-item label="主机名">
              <el-input
                v-model="createForm.hostname"
                placeholder="例如: my-container"
                class="glass-input"
              />
              <div class="form-tip">设置容器的主机名</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 网络与端口 -->
        <el-tab-pane label="网络与端口" name="network">
          <el-form :model="createForm" label-width="140px" class="form-glass">
            <el-form-item label="网络模式">
              <el-select v-model="createForm.network_mode" class="glass-select" style="width: 100%" @focus="loadNetworksForSelect">
                <el-option label="默认网络 (default)" value="default" />
                <el-option
                  v-for="network in availableNetworks"
                  :key="network.Id"
                  :label="`${network.Name} (${network.Driver})`"
                  :value="network.Name"
                />
              </el-select>
              <div class="form-tip">选择容器的网络模式</div>
            </el-form-item>

            <el-form-item label="端口映射">
              <el-input
                v-model="createForm.ports"
                type="textarea"
                :rows="4"
                placeholder="每行一个端口映射，例如:&#10;8080:80&#10;3306:3306&#10;443:443"
                class="glass-input"
              />
              <div class="form-tip">将主机端口映射到容器端口，格式：主机端口:容器端口</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 存储与挂载 -->
        <el-tab-pane label="存储与挂载" name="storage">
          <el-form :model="createForm" label-width="140px" class="form-glass">
            <el-form-item label="数据卷挂载">
              <el-input
                v-model="createForm.volumes"
                type="textarea"
                :rows="4"
                placeholder="每行一个挂载，例如:&#10;/host/data:/container/data&#10;/host/logs:/var/log&#10;/host/config:/etc/config:ro"
                class="glass-input"
              />
              <div class="form-tip">将主机目录挂载到容器内，格式：主机路径:容器路径[:权限]</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 环境变量 -->
        <el-tab-pane label="环境变量" name="environment">
          <el-form :model="createForm" label-width="140px" class="form-glass">
            <el-form-item label="环境变量">
              <div class="env-vars-container">
                <div
                  v-for="(envVar, index) in createForm.env_vars"
                  :key="index"
                  class="env-var-item"
                >
                  <el-input
                    v-model="envVar.key"
                    placeholder="变量名，例如: MYSQL_ROOT_PASSWORD"
                    class="glass-input env-key-input"
                  />
                  <span class="env-separator">=</span>
                  <el-input
                    v-model="envVar.value"
                    placeholder="变量值，例如: 123456"
                    class="glass-input env-value-input"
                  />
                  <el-button
                    @click="removeEnvVar(index)"
                    class="glass-button delete-button env-remove-btn"
                    size="small"
                    :disabled="createForm.env_vars.length === 1"
                  >
                    <i class="fa fa-minus"></i>
                  </el-button>
                </div>
                <el-button
                  @click="addEnvVar"
                  class="glass-button add-button env-add-btn"
                  size="small"
                >
                  <i class="fa fa-plus"></i>
                  添加环境变量
                </el-button>
              </div>
              <div class="form-tip">设置容器的环境变量，格式：变量名=变量值</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 命令与资源 -->
        <el-tab-pane label="命令与资源" name="command">
          <el-form :model="createForm" label-width="140px" class="form-glass">
            <el-form-item label="启动命令">
              <el-input
                v-model="createForm.command"
                placeholder="例如: /bin/bash"
                class="glass-input"
              />
              <div class="form-tip">覆盖镜像的默认启动命令（可选）</div>
            </el-form-item>

            <el-form-item label="命令参数">
              <el-input
                v-model="createForm.args"
                placeholder="例如: --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci"
                class="glass-input"
              />
              <div class="form-tip">传递给镜像的参数，多个参数用空格分隔</div>
            </el-form-item>

            <el-form-item label="内存限制">
              <el-input
                v-model="createForm.memory_limit"
                placeholder="例如: 512m, 1g"
                class="glass-input"
              />
              <div class="form-tip">限制容器使用的内存大小</div>
            </el-form-item>

            <el-form-item label="CPU限制">
              <el-input
                v-model="createForm.cpu_limit"
                placeholder="例如: 0.5, 1.0, 2"
                class="glass-input"
              />
              <div class="form-tip">限制容器使用的CPU核心数</div>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="createDialogVisible = false" class="glass-button">
          <i class="fa fa-times"></i>
          取消
        </el-button>
        <el-button @click="submitCreateContainer" class="glass-button add-button">
          <i class="fa fa-play"></i>
          创建并运行
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { dockerContainerAPI, dockerImageAPI, dockerServerAPI } from '@/api/docker'
import { ElMessage, ElMessageBox } from 'element-plus'
import { nextTick, onMounted, reactive, ref, watch } from 'vue'

// 响应式数据
const loading = ref(false)
const selectedServer = ref('')
const showAllContainers = ref(true)
const logDialogVisible = ref(false)
const logDialogTitle = ref('')
const logContent = ref('')
const logLines = ref(500)
const logContentRef = ref()
const currentLogContainer = ref(null)
const realTimeLogs = ref(false)
const logsWebsocket = ref(null)
const logsWebsocketConnected = ref(false)
const terminalDialogVisible = ref(false)
const terminalDialogTitle = ref('')
const inspectDialogVisible = ref(false)
const inspectDialogTitle = ref('')
const inspectContent = ref('')
const inspectContentRef = ref()
const currentInspectContainer = ref(null)

// 终端相关变量
let terminal: any = null
let fitAddon: any = null
let websocket: any = null
let currentContainer: any = null
const terminalConnected = ref(false)

// 统计数据
const statistics = reactive({
  total_containers: 0,
  running_containers: 0,
  stopped_containers: 0
})

// 数据列表
const dockerServers = ref([])
const containers = ref([])

// 监听服务器选择变化
watch(selectedServer, (newValue) => {
  if (newValue) {
    loadContainers()
  }
})

// 监听显示所有容器变化
watch(showAllContainers, () => {
  if (selectedServer.value) {
    loadContainers()
  }
})

// 初始化终端
const initTerminal = async (container: any) => {
  try {
    currentContainer = container
    terminalConnected.value = false

    // 等待DOM渲染
    await nextTick()

    const terminalElement = document.getElementById('terminal')
    if (!terminalElement) {
      ElMessage.error('终端容器未找到')
      return
    }

    // 动态导入xterm
    const { Terminal } = await import('xterm')
    const { FitAddon } = await import('xterm-addon-fit')
    const { WebLinksAddon } = await import('xterm-addon-web-links')

    // 创建终端实例
    terminal = new Terminal({
      cursorBlink: true,
      cursorStyle: 'block',
      fontSize: 14,
      fontFamily: 'Monaco, Menlo, "Ubuntu Mono", "Consolas", monospace',
      theme: {
        background: '#1a1a1a',
        foreground: '#ffffff',
        cursor: '#00ff00',
        selection: '#3e3e3e',
        black: '#000000',
        red: '#cd0000',
        green: '#00cd00',
        yellow: '#cdcd00',
        blue: '#0000ee',
        magenta: '#cd00cd',
        cyan: '#00cdcd',
        white: '#e5e5e5',
        brightBlack: '#7f7f7f',
        brightRed: '#ff0000',
        brightGreen: '#00ff00',
        brightYellow: '#ffff00',
        brightBlue: '#5c5cff',
        brightMagenta: '#ff00ff',
        brightCyan: '#00ffff',
        brightWhite: '#ffffff'
      },
      scrollback: 1000,
      allowTransparency: false,
      convertEol: true
    })

    // 添加插件
    fitAddon = new FitAddon()
    const webLinksAddon = new WebLinksAddon()

    terminal.loadAddon(fitAddon)
    terminal.loadAddon(webLinksAddon)

    // 打开终端
    terminal.open(terminalElement)

    // 调整终端大小
    setTimeout(() => {
      fitAddon.fit()
      connectToContainer()
    }, 100)

    // 监听用户输入
    terminal.onData((data: string) => {
      if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify({
          type: 'input',
          data: data
        }))
      }
    })

    // 监听终端大小变化
    terminal.onResize((size: any) => {
      if (websocket && websocket.readyState === WebSocket.OPEN) {
        websocket.send(JSON.stringify({
          type: 'resize',
          cols: size.cols,
          rows: size.rows
        }))
      }
    })

  } catch (error) {
    console.error('初始化终端失败:', error)
    ElMessage.error('初始化终端失败')
  }
}

// 连接到容器
const connectToContainer = async () => {
  try {
    // 获取token
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未找到认证令牌')
      return
    }

    // 使用统一的WebSocket配置工具
    const { getDockerTerminalWebSocketUrl } = await import('@/utils/websocket-config')
    const wsUrl = getDockerTerminalWebSocketUrl(selectedServer.value, currentContainer.id, token)

    terminal.writeln('\x1b[33m正在连接容器终端...\x1b[0m')

    websocket = new WebSocket(wsUrl)

    websocket.onopen = () => {
      terminal.writeln('\x1b[32mWebSocket连接已建立\x1b[0m')

      // 发送连接请求
      websocket.send(JSON.stringify({
        type: 'connect',
        terminal_size: {
          cols: terminal.cols,
          rows: terminal.rows
        }
      }))
    }

    websocket.onmessage = (event: MessageEvent) => {
      try {
        const data = JSON.parse(event.data)
        handleWebSocketMessage(data)
      } catch (error) {
        console.error('解析WebSocket消息失败:', error)
      }
    }

    websocket.onclose = (event: CloseEvent) => {
      terminal.writeln(`\r\n\x1b[31m连接已断开 (${event.code})\x1b[0m`)
      terminalConnected.value = false
    }

    websocket.onerror = (error: Event) => {
      console.error('WebSocket错误:', error)
      terminal.writeln('\r\n\x1b[31m连接错误\x1b[0m')
      terminalConnected.value = false
    }

  } catch (error) {
    console.error('连接容器失败:', error)
    ElMessage.error('连接容器失败')
  }
}

// 处理WebSocket消息
const handleWebSocketMessage = (data: any) => {
  switch (data.type) {
    case 'status':
      if (data.status === 'websocket_connected') {
        terminal.writeln('\x1b[32m正在进入容器...\x1b[0m')
      }
      break
    case 'connected':
      terminal.writeln('\x1b[32m容器终端连接成功\x1b[0m')
      terminalConnected.value = true
      break
    case 'output':
      terminal.write(data.data)
      break
    case 'error':
      terminal.writeln(`\r\n\x1b[31m错误: ${data.message}\x1b[0m`)
      break
  }
}

// 清理终端
const cleanupTerminal = () => {
  // 先重置连接状态，避免状态显示闪烁
  terminalConnected.value = false

  if (websocket) {
    websocket.close()
    websocket = null
  }
  if (terminal) {
    terminal.dispose()
    terminal = null
  }
  if (fitAddon) {
    fitAddon = null
  }
}

// 监听终端对话框关闭
watch(terminalDialogVisible, (newValue) => {
  if (!newValue) {
    cleanupTerminal()
  }
})

// 页面加载
onMounted(() => {
  loadData()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    // 先加载服务器列表，如果有服务器会自动加载容器数据
    await loadDockerServers()
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载Docker服务器列表
const loadDockerServers = async () => {
  try {
    const response = await dockerServerAPI.getServers()
    dockerServers.value = response.data.results || response.data || []

    // 如果有服务器且没有选中的服务器，默认选择第一个
    if (dockerServers.value.length > 0 && !selectedServer.value) {
      selectedServer.value = dockerServers.value[0].id
      // 立即加载容器数据
      await loadContainers()
    }
  } catch (error) {
    console.error('加载Docker服务器失败:', error)
    ElMessage.error('加载Docker服务器失败')
  }
}

// 加载容器列表
const loadContainers = async () => {
  if (!selectedServer.value) {
    containers.value = []
    return
  }

  loading.value = true
  try {
    const response = await dockerContainerAPI.getContainers(selectedServer.value, {
      all: showAllContainers.value
    })
    if (response.data.success) {
      containers.value = response.data.containers || []
      // 基于实际容器数据计算统计信息
      updateStatisticsFromContainers(containers.value)
    } else {
      ElMessage.error(response.data.message || '加载容器列表失败')
      containers.value = []
      resetStatistics()
    }
  } catch (error) {
    console.error('加载容器列表失败:', error)
    ElMessage.error('加载容器列表失败')
    containers.value = []
    resetStatistics()
  } finally {
    loading.value = false
  }
}

// 基于容器数据更新统计信息
const updateStatisticsFromContainers = (containerList: any[]) => {
  const total = containerList.length
  const running = containerList.filter(c => {
    // 多种状态判断方式
    const state = c.state?.toLowerCase() || ''
    const status = c.status?.toLowerCase() || ''

    return state === 'running' ||
           status.includes('up') ||
           status.includes('running')
  }).length
  const stopped = total - running

  Object.assign(statistics, {
    total_containers: total,
    running_containers: running,
    stopped_containers: stopped
  })
}

// 重置统计数据
const resetStatistics = () => {
  Object.assign(statistics, {
    total_containers: 0,
    running_containers: 0,
    stopped_containers: 0
  })
}

// 加载统计数据（备用，主要用基于容器数据的统计）
const loadStatistics = async () => {
  try {
    const response = await dockerServerAPI.getStatistics()
    // 映射后端返回的字段名到前端期望的字段名
    Object.assign(statistics, {
      total_containers: response.data.total_containers || 0,
      running_containers: response.data.running_containers || 0,
      stopped_containers: (response.data.total_containers || 0) - (response.data.running_containers || 0)
    })
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 不显示错误消息，因为我们有基于容器数据的统计
  }
}

// 刷新容器列表
const refreshContainers = () => {
  loadData()
  ElMessage.success('容器列表已刷新')
}

// 创建容器相关变量
const createDialogVisible = ref(false)
const availableImages = ref([])
const availableNetworks = ref([])
const activeTab = ref('basic')

// 创建容器表单
const createForm = reactive({
  image_source: 'local', // local: 选择本地镜像, manual: 手动输入镜像名
  image_name: '',
  manual_image_name: '',
  container_name: '',
  ports: '',
  volumes: '',
  env_vars: [{ key: '', value: '' }],
  command: '',
  args: '',
  restart_policy: 'no',
  auto_remove: false,
  privileged: false,
  user: '',
  working_dir: '',
  hostname: '',
  network_mode: 'default',
  memory_limit: '',
  cpu_limit: ''
})

// 显示创建容器对话框
const showCreateContainer = async () => {
  if (!selectedServer.value) {
    ElMessage.warning('请先选择Docker服务器')
    return
  }

  // 加载可用镜像
  await loadAvailableImages()
  createDialogVisible.value = true
}

// 加载可用镜像
const loadAvailableImages = async () => {
  try {
    const response = await dockerImageAPI.getImages(selectedServer.value)
    if (response.data.success) {
      availableImages.value = response.data.images || []
    } else {
      ElMessage.error('加载镜像列表失败')
      availableImages.value = []
    }
  } catch (error) {
    console.error('加载镜像列表失败:', error)
    ElMessage.error('加载镜像列表失败')
    availableImages.value = []
  }
}

// 加载网络列表
const loadNetworksForSelect = async () => {
  if (!selectedServer.value || availableNetworks.value.length > 0) return

  try {
    const { dockerNetworkAPI } = await import('@/api/docker')
    const response = await dockerNetworkAPI.getNetworks(selectedServer.value)
    if (response.data.success) {
      availableNetworks.value = response.data.networks || []
    } else {
      console.error('加载网络列表失败:', response.data.message)
      availableNetworks.value = []
    }
  } catch (error) {
    console.error('加载网络列表失败:', error)
    availableNetworks.value = []
  }
}

// 环境变量操作
const addEnvVar = () => {
  createForm.env_vars.push({ key: '', value: '' })
}

const removeEnvVar = (index) => {
  if (createForm.env_vars.length > 1) {
    createForm.env_vars.splice(index, 1)
  }
}

// 提交创建容器
const submitCreateContainer = async () => {
  // 获取最终的镜像名称
  const finalImageName = createForm.image_source === 'local' ? createForm.image_name : createForm.manual_image_name

  if (!finalImageName) {
    ElMessage.warning(createForm.image_source === 'local' ? '请选择镜像' : '请输入镜像名称')
    return
  }

  try {
    loading.value = true

    // 处理表单数据
    const ports = createForm.ports ? createForm.ports.split('\n').filter(p => p.trim()) : []
    const volumes = createForm.volumes ? createForm.volumes.split('\n').filter(v => v.trim()) : []

    // 处理环境变量
    let env_vars = {}
    createForm.env_vars.forEach(envVar => {
      if (envVar.key && envVar.key.trim()) {
        env_vars[envVar.key.trim()] = envVar.value || ''
      }
    })

    const response = await dockerImageAPI.run(
      selectedServer.value,
      finalImageName,
      {
        container_name: createForm.container_name || undefined,
        ports: ports,
        volumes: volumes,
        env_vars: env_vars,
        command: createForm.command || undefined,
        args: createForm.args || undefined,
        restart_policy: createForm.restart_policy,
        auto_remove: createForm.auto_remove,
        privileged: createForm.privileged,
        user: createForm.user || undefined,
        working_dir: createForm.working_dir || undefined,
        hostname: createForm.hostname || undefined,
        network_mode: createForm.network_mode,
        memory_limit: createForm.memory_limit || undefined,
        cpu_limit: createForm.cpu_limit || undefined
      }
    )

    if (response.data.success) {
      ElMessage.success('容器创建成功')
      createDialogVisible.value = false
      resetCreateForm()
      await loadContainers()
    } else {
      ElMessage.error(response.data.message || '创建容器失败')
    }
  } catch (error) {
    console.error('创建容器失败:', error)
    ElMessage.error('创建容器失败')
  } finally {
    loading.value = false
  }
}

// 重置创建表单
const resetCreateForm = () => {
  createForm.image_source = 'local'
  createForm.image_name = ''
  createForm.manual_image_name = ''
  createForm.container_name = ''
  createForm.ports = ''
  createForm.volumes = ''
  createForm.env_vars = [{ key: '', value: '' }]
  createForm.command = ''
  createForm.args = ''
  createForm.restart_policy = 'no'
  createForm.auto_remove = false
  createForm.privileged = false
  createForm.user = ''
  createForm.working_dir = ''
  createForm.hostname = ''
  createForm.network_mode = 'default'
  createForm.memory_limit = ''
  createForm.cpu_limit = ''
}

// 清理停止的容器
const cleanupContainers = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清理所有停止的容器吗？此操作不可恢复。',
      '确认清理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    if (!selectedServer.value) {
      ElMessage.error('请先选择Docker服务器')
      return
    }

    // 使用Docker的prune命令清理所有停止的容器
    const response = await dockerContainerAPI.pruneContainers(selectedServer.value)

    if (response.data.success) {
      ElMessage.success(response.data.message || '容器清理完成')
    } else {
      ElMessage.error(response.data.message || '清理失败')
    }

    await loadContainers()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理容器失败:', error)
      ElMessage.error('清理失败')
    }
  }
}

// 容器操作
const startContainer = async (container: any) => {
  container.loading = true
  try {
    const response = await dockerContainerAPI.startContainer(selectedServer.value, container.id)
    if (response.data.success) {
      ElMessage.success(`容器 ${container.name} 启动成功`)
      await loadContainers()
    } else {
      ElMessage.error(response.data.message || `启动容器 ${container.name} 失败`)
    }
  } catch (error) {
    console.error('启动容器失败:', error)
    ElMessage.error('启动失败')
  } finally {
    container.loading = false
  }
}

const stopContainer = async (container: any) => {
  container.loading = true
  try {
    const response = await dockerContainerAPI.stopContainer(selectedServer.value, container.id)
    if (response.data.success) {
      ElMessage.success(`容器 ${container.name} 停止成功`)
      await loadContainers()
    } else {
      ElMessage.error(response.data.message || `停止容器 ${container.name} 失败`)
    }
  } catch (error) {
    console.error('停止容器失败:', error)
    ElMessage.error('停止失败')
  } finally {
    container.loading = false
  }
}

const restartContainer = async (container: any) => {
  container.loading = true
  try {
    const response = await dockerContainerAPI.restartContainer(selectedServer.value, container.id)
    if (response.data.success) {
      ElMessage.success(`容器 ${container.name} 重启成功`)
      await loadContainers()
    } else {
      ElMessage.error(response.data.message || `重启容器 ${container.name} 失败`)
    }
  } catch (error) {
    console.error('重启容器失败:', error)
    ElMessage.error('重启失败')
  } finally {
    container.loading = false
  }
}

const viewLogs = async (container: any) => {
  try {
    // 保存当前容器信息
    currentLogContainer.value = container

    // 显示日志查看对话框
    logDialogVisible.value = true
    logDialogTitle.value = `容器 ${container.name} 日志`

    // 清空之前的日志内容
    logContent.value = ''

    // 默认开启实时日志
    realTimeLogs.value = true

    // 等待DOM更新后初始化实时日志
    nextTick(() => {
      initRealTimeLogs()
    })
  } catch (error) {
    console.error('初始化日志查看失败:', error)
    ElMessage.error('初始化日志查看失败')
  }
}

// 日志操作方法
const refreshLogs = async () => {
  if (currentLogContainer.value && !realTimeLogs.value) {
    // 只有在静态模式下才允许手动刷新
    try {
      const response = await dockerContainerAPI.getContainerLogs(selectedServer.value, currentLogContainer.value.id, { lines: logLines.value })
      if (response.data.success) {
        logContent.value = response.data.logs || '暂无日志'
        nextTick(() => {
          scrollToBottom()
        })
        ElMessage.success('日志已刷新')
      } else {
        ElMessage.error(response.data.message || '获取容器日志失败')
      }
    } catch (error) {
      console.error('刷新日志失败:', error)
      ElMessage.error('刷新日志失败')
    }
  }
}

const clearLogs = () => {
  logContent.value = ''
  ElMessage.success('日志已清空')
}

const scrollToTop = () => {
  if (logContentRef.value) {
    logContentRef.value.scrollTop = 0
  }
}

const scrollToBottom = () => {
  if (logContentRef.value) {
    logContentRef.value.scrollTop = logContentRef.value.scrollHeight
  }
}

// 实时日志相关方法
const toggleRealTimeLogs = (enabled: boolean) => {
  if (enabled) {
    initRealTimeLogs()
  } else {
    stopRealTimeLogs()
  }
}

const initRealTimeLogs = async () => {
  if (!currentLogContainer.value) return

  try {
    // 获取当前用户token
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('未找到认证令牌')
      return
    }

    // 使用统一的WebSocket配置工具
    const { getDockerLogsWebSocketUrl } = await import('@/utils/websocket-config')
    const wsUrl = getDockerLogsWebSocketUrl(selectedServer.value, currentLogContainer.value.id, token)

    console.log('连接实时日志WebSocket:', wsUrl)

    // 创建WebSocket连接
    logsWebsocket.value = new WebSocket(wsUrl)

    logsWebsocket.value.onopen = () => {
      console.log('实时日志WebSocket连接已建立')
      logsWebsocketConnected.value = true

      // 发送开始日志消息
      logsWebsocket.value.send(JSON.stringify({
        type: 'start_logs',
        lines: logLines.value,
        follow: true
      }))
    }

    logsWebsocket.value.onmessage = (event) => {
      handleLogsWebSocketMessage(JSON.parse(event.data))
    }

    logsWebsocket.value.onerror = (error) => {
      console.error('实时日志WebSocket错误:', error)
      logsWebsocketConnected.value = false
    }

    logsWebsocket.value.onclose = () => {
      console.log('实时日志WebSocket连接已关闭')
      logsWebsocketConnected.value = false
    }

  } catch (error) {
    console.error('初始化实时日志失败:', error)
    ElMessage.error('初始化实时日志失败')
  }
}

const stopRealTimeLogs = () => {
  if (logsWebsocket.value) {
    // 发送停止日志消息
    logsWebsocket.value.send(JSON.stringify({
      type: 'stop_logs'
    }))

    // 关闭WebSocket连接
    logsWebsocket.value.close()
    logsWebsocket.value = null
    logsWebsocketConnected.value = false
  }
}

const handleLogsWebSocketMessage = (data: any) => {
  switch (data.type) {
    case 'status':
      console.log('日志状态:', data.message)
      break
    case 'logs_started':
      console.log('日志开始:', data.message)
      break
    case 'log_data':
      // 追加日志数据
      logContent.value += data.data
      // 自动滚动到底部
      nextTick(() => {
        scrollToBottom()
      })
      break
    case 'error':
      console.error('日志错误:', data.message)
      ElMessage.error(data.message)
      break
    default:
      console.log('未知日志消息类型:', data.type)
  }
}

// 清理实时日志连接
const cleanupLogsWebSocket = () => {
  if (logsWebsocket.value) {
    logsWebsocket.value.close()
    logsWebsocket.value = null
    logsWebsocketConnected.value = false
  }
}

// 关闭日志对话框
const closeLogsDialog = () => {
  // 停止实时日志
  if (realTimeLogs.value) {
    stopRealTimeLogs()
  }

  // 清理WebSocket连接
  cleanupLogsWebSocket()

  // 重置状态
  realTimeLogs.value = false
  logContent.value = ''
  currentLogContainer.value = null

  // 关闭对话框
  logDialogVisible.value = false
}

const execContainer = (container: any) => {
  terminalDialogVisible.value = true
  terminalDialogTitle.value = `容器 ${container.name} 终端`

  // 等待对话框渲染完成后初始化终端
  nextTick(() => {
    initTerminal(container)
  })
}

// 查看容器详情
const inspectContainer = async (container: any) => {
  try {
    // 保存当前容器信息
    currentInspectContainer.value = container

    // 显示详情对话框
    inspectDialogVisible.value = true
    inspectDialogTitle.value = `容器 ${container.name} 详细信息`

    // 清空之前的内容
    inspectContent.value = '正在加载容器详细信息...'

    // 获取容器详细信息
    const response = await dockerContainerAPI.inspectContainer(selectedServer.value, container.id)
    if (response.data.success) {
      // 格式化JSON显示
      inspectContent.value = JSON.stringify(response.data.data, null, 2)

      // 等待DOM更新后滚动到顶部
      nextTick(() => {
        scrollInspectToTop()
      })
    } else {
      inspectContent.value = `获取容器详细信息失败: ${response.data.message}`
      ElMessage.error(response.data.message || '获取容器详细信息失败')
    }
  } catch (error) {
    console.error('获取容器详细信息失败:', error)
    inspectContent.value = `获取容器详细信息失败: ${error.message}`
    ElMessage.error('获取容器详细信息失败')
  }
}

// 刷新容器详情
const refreshInspect = async () => {
  if (currentInspectContainer.value) {
    await inspectContainer(currentInspectContainer.value)
    ElMessage.success('容器详情已刷新')
  }
}

// 复制容器详情数据
const copyInspectData = async () => {
  try {
    await navigator.clipboard.writeText(inspectContent.value)
    ElMessage.success('容器详情已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

// 滚动到顶部
const scrollInspectToTop = () => {
  if (inspectContentRef.value) {
    inspectContentRef.value.scrollTop = 0
  }
}

// 滚动到底部
const scrollInspectToBottom = () => {
  if (inspectContentRef.value) {
    inspectContentRef.value.scrollTop = inspectContentRef.value.scrollHeight
  }
}

// 关闭详情对话框
const closeInspectDialog = () => {
  // 重置状态
  inspectContent.value = ''
  currentInspectContainer.value = null

  // 关闭对话框
  inspectDialogVisible.value = false
}

const deleteContainer = async (container: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除容器 "${container.name}" 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    container.loading = true
    const response = await dockerContainerAPI.removeContainer(selectedServer.value, container.id, false)
    if (response.data.success) {
      ElMessage.success(`容器 ${container.name} 删除成功`)
      await loadContainers()
    } else {
      ElMessage.error(response.data.message || `删除容器 ${container.name} 失败`)
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除容器失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    container.loading = false
  }
}

// 工具函数
const getStatusType = (status: string) => {
  switch (status) {
    case 'running': return 'success'
    case 'stopped': return 'info'
    case 'exited': return 'warning'
    case 'error': return 'danger'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'running': return '运行中'
    case 'stopped': return '已停止'
    case 'exited': return '已退出'
    case 'error': return '错误'
    default: return '未知'
  }
}

const formatPorts = (ports: any) => {
  if (!ports || ports === '') return '无'
  return ports
}

const formatTime = (time: string) => {
  if (!time) return '未知'
  return new Date(time).toLocaleString('zh-CN')
}
</script>

<style scoped>
/* 使用与Docker服务器配置页面完全相同的样式 */
.ansible-audit-container {
  min-height: 100vh;
  background: linear-gradient(
    135deg,
    rgba(0, 0, 0, 0.9) 0%,
    rgba(20, 20, 40, 0.95) 50%,
    rgba(0, 0, 0, 0.9) 100%
  );
  overflow-x: hidden;
}

.starry-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
  pointer-events: none;
}

.stars, .stars2, .stars3 {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: transparent;
}

.stars {
  background-image:
    radial-gradient(2px 2px at 20px 30px, #eee, transparent),
    radial-gradient(2px 2px at 40px 70px, rgba(255,255,255,0.8), transparent),
    radial-gradient(1px 1px at 90px 40px, #fff, transparent);
  background-repeat: repeat;
  background-size: 200px 100px;
  animation: zoom 20s infinite linear;
}

.stars2 {
  background-image:
    radial-gradient(1px 1px at 40px 60px, #fff, transparent),
    radial-gradient(1px 1px at 120px 10px, rgba(255,255,255,0.7), transparent);
  background-repeat: repeat;
  background-size: 300px 200px;
  animation: zoom 40s infinite linear;
}

.stars3 {
  background-image:
    radial-gradient(1px 1px at 10px 10px, rgba(255,255,255,0.5), transparent);
  background-repeat: repeat;
  background-size: 400px 300px;
  animation: zoom 60s infinite linear;
}

@keyframes zoom {
  from { transform: scale(1); }
  to { transform: scale(1.5); }
}

.audit-content {
  position: relative;
  z-index: 10;
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.glass-effect {
  background: rgba(164, 244, 186, 0.1);
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 12px;
  backdrop-filter: blur(20px);
  box-shadow:
    0 8px 32px rgba(0, 0, 0, 0.3),
    inset 0 1px 0 rgba(255, 255, 255, 0.1);
}

.page-header {
  margin-bottom: 30px;
  padding: 30px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 30px;
}

.title-section h1 {
  color: rgba(255, 255, 255, 0.95);
  font-size: 28px;
  font-weight: 600;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.title-section h1 i {
  color: #a4f4ba;
  margin-right: 12px;
}

.page-subtitle {
  color: rgba(255, 255, 255, 0.7);
  font-size: 14px;
  margin: 0;
}

.stats-section {
  display: flex;
  gap: 20px;
}

.stat-card {
  padding: 20px;
  text-align: center;
  min-width: 120px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #a4f4ba;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.search-filters {
  margin-bottom: 30px;
  padding: 20px;
}

.search-form {
  margin: 0;
}

.audit-table-section {
  padding: 30px;
  margin-bottom: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: rgba(255, 255, 255, 0.95);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.section-title i {
  color: #a4f4ba;
}

.config-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.config-name i {
  color: #00eaff;
}

.time-text, .port-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 12px;
}

.port-text {
  font-family: monospace;
}

.server-select {
  width: 200px;
  margin-right: 10px;
}

/* 按钮样式 */
.glass-button {
  background: rgba(164, 244, 186, 0.15) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: rgba(255, 255, 255, 0.9) !important;
  transition: all 0.3s ease !important;
  backdrop-filter: blur(10px) !important;
  border-radius: 8px !important;
  padding: 8px 16px !important;
  font-size: 14px !important;
  font-weight: 500 !important;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;

  &:hover {
    background: rgba(164, 244, 186, 0.25) !important;
    border-color: rgba(164, 244, 186, 0.5) !important;
    color: #ffffff !important;
    box-shadow: 0 4px 16px rgba(164, 244, 186, 0.2) !important;
  }

  i {
    margin-right: 4px !important;
    color: #00eaff !important;
  }

  &.refresh-button {
    background: rgba(138, 43, 226, 0.2) !important;
    border-color: rgba(138, 43, 226, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(138, 43, 226, 0.3) !important;
      border-color: rgba(138, 43, 226, 0.6) !important;
      box-shadow: 0 4px 16px rgba(138, 43, 226, 0.3) !important;
    }

    i {
      color: #8a2be2 !important;
    }
  }

  &.sync-button {
    background: rgba(59, 130, 246, 0.2) !important;
    border-color: rgba(59, 130, 246, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(59, 130, 246, 0.3) !important;
      border-color: rgba(59, 130, 246, 0.6) !important;
      box-shadow: 0 4px 16px rgba(59, 130, 246, 0.3) !important;
    }

    i {
      color: #3b82f6 !important;
    }
  }

  &.add-button {
    background: rgba(34, 197, 94, 0.2) !important;
    border-color: rgba(34, 197, 94, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(34, 197, 94, 0.3) !important;
      border-color: rgba(34, 197, 94, 0.6) !important;
      box-shadow: 0 4px 16px rgba(34, 197, 94, 0.3) !important;
    }

    i {
      color: #22c55e !important;
    }
  }

  &.import-button {
    background: rgba(6, 182, 212, 0.2) !important;
    border-color: rgba(6, 182, 212, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(6, 182, 212, 0.3) !important;
      border-color: rgba(6, 182, 212, 0.6) !important;
      box-shadow: 0 4px 16px rgba(6, 182, 212, 0.3) !important;
    }

    i {
      color: #06b6d4 !important;
    }
  }

  &.delete-button {
    background: rgba(239, 68, 68, 0.2) !important;
    border-color: rgba(239, 68, 68, 0.4) !important;
    color: #ffffff !important;

    &:hover {
      background: rgba(239, 68, 68, 0.3) !important;
      border-color: rgba(239, 68, 68, 0.6) !important;
      box-shadow: 0 4px 16px rgba(239, 68, 68, 0.3) !important;
    }

    i {
      color: #ef4444 !important;
    }
  }
}

/* 表格样式 */
:deep(.audit-table) {
  background: transparent !important;

  .el-table__header {
    background: rgba(164, 244, 186, 0.1) !important;
  }

  .el-table__header th {
    background: transparent !important;
    border-bottom: 1px solid rgba(164, 244, 186, 0.3) !important;
    color: rgba(255, 255, 255, 0.9) !important;
    font-weight: 600 !important;
  }

  .el-table__body tr {
    background: transparent !important;

    &:hover {
      background: rgba(164, 244, 186, 0.05) !important;
    }
  }

  .el-table__body td {
    border-bottom: 1px solid rgba(164, 244, 186, 0.1) !important;
    color: rgba(255, 255, 255, 0.8) !important;
  }
}

.action-buttons {
  display: flex;
  gap: 5px;
  align-items: center;
  flex-wrap: nowrap;
  justify-content: flex-start;
}

.action-buttons .glass-button {
  padding: 5px 10px !important;
  font-size: 12px;
  white-space: nowrap;
  width: auto !important;
  min-width: auto !important;
}

/* 日志对话框样式 */
.log-dialog {
  --el-dialog-bg-color: rgba(26, 26, 26, 0.95);
  --el-dialog-border-radius: 12px;
}

.log-dialog .el-dialog__header {
  padding: 0;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.log-dialog .el-dialog__body {
  padding: 0;
  background: #0a0a0a;
}

.log-dialog .el-dialog__footer {
  padding: 0;
  border-top: 1px solid rgba(164, 244, 186, 0.2);
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, rgba(26, 26, 26, 0.95) 0%, rgba(42, 42, 42, 0.95) 100%);
  border-radius: 12px 12px 0 0;
  backdrop-filter: blur(10px);
}

.log-title {
  display: flex;
  align-items: center;
  color: #a4f4ba;
  font-weight: 600;
  font-size: 16px;
}

.log-icon {
  margin-right: 8px;
  color: #00ff00;
  font-size: 18px;
}

.log-controls {
  display: flex;
  gap: 8px;
}

.log-container {
  background: #0a0a0a;
  padding: 0;
  height: 70vh;
  min-height: 500px;
  position: relative;
  overflow: hidden;
}

.log-content {
  width: 100%;
  height: 100%;
  background: #0a0a0a;
  border: none;
  outline: none;
  overflow-y: auto;
  padding: 16px;
  box-sizing: border-box;

  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(164, 244, 186, 0.1);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(164, 244, 186, 0.3);
    border-radius: 4px;

    &:hover {
      background: rgba(164, 244, 186, 0.5);
    }
  }
}

.log-text {
  color: #00ff00;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  background: transparent;
}

.log-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, rgba(26, 26, 26, 0.95) 0%, rgba(42, 42, 42, 0.95) 100%);
  border-radius: 0 0 12px 12px;
  backdrop-filter: blur(10px);
}

.log-info {
  flex: 1;
}

.log-tip {
  color: rgba(164, 244, 186, 0.7);
  font-size: 12px;
  display: flex;
  align-items: center;
}

.log-tip i {
  margin-right: 6px;
  color: #00bfff;
}

.log-status {
  margin-left: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  background: rgba(255, 0, 0, 0.1);
  border: 1px solid rgba(255, 0, 0, 0.3);
  color: #ff6b6b;
  font-size: 11px;
  transition: all 0.3s ease;
}

.log-status.connected {
  background: rgba(0, 255, 0, 0.1);
  border-color: rgba(0, 255, 0, 0.3);
  color: #00ff00;
}

.log-status i {
  margin-right: 4px;
  font-size: 8px;
}

.log-actions {
  display: flex;
  gap: 8px;
}

/* 终端对话框样式 */
.terminal-dialog {
  --el-dialog-bg-color: rgba(26, 26, 26, 0.95);
  --el-dialog-border-radius: 12px;
}

/* 详情对话框样式 */
.inspect-dialog {
  --el-dialog-bg-color: rgba(26, 26, 26, 0.95);
  --el-dialog-border-radius: 12px;
}

.inspect-dialog .el-dialog__header {
  padding: 0;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.inspect-dialog .el-dialog__body {
  padding: 0;
  background: #0a0a0a;
}

.inspect-dialog .el-dialog__footer {
  padding: 0;
  border-top: 1px solid rgba(164, 244, 186, 0.2);
}

.inspect-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, rgba(26, 26, 26, 0.95) 0%, rgba(42, 42, 42, 0.95) 100%);
  border-radius: 12px 12px 0 0;
  backdrop-filter: blur(10px);
}

.inspect-title {
  display: flex;
  align-items: center;
  color: #a4f4ba;
  font-weight: 600;
  font-size: 16px;
}

.inspect-icon {
  margin-right: 8px;
  color: #00ff00;
  font-size: 18px;
}

.inspect-controls {
  display: flex;
  gap: 8px;
}

.inspect-container {
  background: #0a0a0a;
  padding: 0;
  height: 70vh;
  min-height: 500px;
  position: relative;
  overflow: hidden;
}

.inspect-content {
  width: 100%;
  height: 100%;
  background: #0a0a0a;
  border: none;
  outline: none;
  overflow-y: auto;
  padding: 16px;
  box-sizing: border-box;

  /* 自定义滚动条 */
  &::-webkit-scrollbar {
    width: 8px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(164, 244, 186, 0.1);
    border-radius: 4px;
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(164, 244, 186, 0.3);
    border-radius: 4px;

    &:hover {
      background: rgba(164, 244, 186, 0.5);
    }
  }
}

.inspect-text {
  color: #00ffff;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
  background: transparent;
}

.inspect-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, rgba(26, 26, 26, 0.95) 0%, rgba(42, 42, 42, 0.95) 100%);
  border-radius: 0 0 12px 12px;
  backdrop-filter: blur(10px);
}

.inspect-info {
  flex: 1;
}

.inspect-tip {
  color: rgba(164, 244, 186, 0.7);
  font-size: 12px;
  display: flex;
  align-items: center;
}

.inspect-tip i {
  margin-right: 6px;
  color: #00bfff;
}

.inspect-actions {
  display: flex;
  gap: 8px;
}

.terminal-dialog .el-dialog__header {
  padding: 0;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);
}

.terminal-dialog .el-dialog__body {
  padding: 0;
  background: #0a0a0a;
}

.terminal-dialog .el-dialog__footer {
  padding: 0;
  border-top: 1px solid rgba(164, 244, 186, 0.2);
}

.terminal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: linear-gradient(135deg, rgba(26, 26, 26, 0.95) 0%, rgba(42, 42, 42, 0.95) 100%);
  border-radius: 12px 12px 0 0;
  backdrop-filter: blur(10px);
}

.terminal-title {
  display: flex;
  align-items: center;
  color: #a4f4ba;
  font-weight: 600;
  font-size: 16px;
}

.terminal-icon {
  margin-right: 8px;
  color: #00ff00;
  font-size: 18px;
}

.terminal-controls {
  display: flex;
  align-items: center;
}

.terminal-status {
  display: flex;
  align-items: center;
  padding: 4px 12px;
  border-radius: 20px;
  background: rgba(255, 0, 0, 0.1);
  border: 1px solid rgba(255, 0, 0, 0.3);
  color: #ff6b6b;
  font-size: 12px;
  transition: all 0.3s ease;
}

.terminal-status.connected {
  background: rgba(0, 255, 0, 0.1);
  border-color: rgba(0, 255, 0, 0.3);
  color: #00ff00;
}

.terminal-status i {
  margin-right: 6px;
  font-size: 8px;
}

.terminal-container {
  background: #0a0a0a;
  padding: 0;
  height: 70vh;
  min-height: 500px;
  position: relative;
  overflow: hidden;
}

.terminal {
  width: 100%;
  height: 100%;
  background: #0a0a0a;
  border: none;
  outline: none;
}

.terminal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, rgba(26, 26, 26, 0.95) 0%, rgba(42, 42, 42, 0.95) 100%);
  border-radius: 0 0 12px 12px;
  backdrop-filter: blur(10px);
}

.terminal-info {
  flex: 1;
}

.terminal-tip {
  color: rgba(164, 244, 186, 0.7);
  font-size: 12px;
  display: flex;
  align-items: center;
}

.terminal-tip i {
  margin-right: 6px;
  color: #ffd700;
}

.terminal-actions {
  display: flex;
  gap: 8px;
}

/* 玻璃按钮样式 */
.glass-button {
  background: rgba(164, 244, 186, 0.2) !important;
  border: 1px solid rgba(164, 244, 186, 0.3) !important;
  color: #a4f4ba !important;
  backdrop-filter: blur(10px);
  border-radius: 6px;
}

.glass-button:hover {
  background: rgba(164, 244, 186, 0.3) !important;
  border-color: rgba(164, 244, 186, 0.5) !important;
}

.glass-button.danger {
  background: rgba(255, 107, 107, 0.2) !important;
  border-color: rgba(255, 107, 107, 0.3) !important;
  color: #ff6b6b !important;
}

.glass-button.danger:hover {
  background: rgba(255, 107, 107, 0.3) !important;
  border-color: rgba(255, 107, 107, 0.5) !important;
}

/* 镜像来源选择样式 */
.image-source-group {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.image-source-radio {
  width: 100%;
  margin: 0;
  height: auto;
}

.image-source-radio .el-radio__input {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 1;
}

.image-source-radio .el-radio__label {
  padding-left: 0;
  width: 100%;
}

.image-source-option {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px 16px 16px 50px;
  border: 1px solid rgba(164, 244, 186, 0.2);
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  width: 100%;
  cursor: pointer;
  position: relative;
}

.image-source-radio:hover .image-source-option {
  border-color: rgba(164, 244, 186, 0.4);
  background: rgba(0, 0, 0, 0.5);
}

.image-source-radio.is-checked .image-source-option {
  border-color: #a4f4ba;
  background: rgba(164, 244, 186, 0.1);
}

.image-source-option i {
  font-size: 20px;
  color: #a4f4ba;
  min-width: 20px;
  margin-top: 2px;
}

.image-source-content {
  flex: 1;
}

.image-source-title {
  color: #a4f4ba;
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 4px;
}

.image-source-desc {
  color: rgba(164, 244, 186, 0.7);
  font-size: 12px;
  line-height: 1.4;
}
</style>
